﻿using Newtonsoft.Json.Linq;
using Raffles.OA.Utility;
using Raffles.OA.Data;
using Raffles.OA.WebApp.App_Start;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Raffles.OA.WebApp.Areas.Manage.Controllers
{
    /// <summary>
    /// 代码生成
    /// </summary>
    public class GeneratorController : BaseActionController
    {
        //--新增表备注：
        //EXEC sys.sp_addextendedproperty N'MS_Description', N'表备注内容', N'SCHEMA', N'dbo',N'table', N'表名';

        //--修改表备注：
        //EXEC sys.sp_updateextendedproperty N'MS_Description', N'表备注内容', N'SCHEMA', N'dbo',N'table', N'表名';

        #region 私有方法
        /// <summary>
        /// 获取所有表的主键、主键名称、记录数
        /// </summary>
        /// <returns></returns>
        private List<TableVo> GetTableDetailList()
        {
            string strSql = @"SELECT (SELECT name FROM sysobjects as t WHERE xtype = 'U' and t.id = sc.id) TableName,
                                     sc.id Id,sc.name TableKey,sysobjects.name TableKeyName,sysindexes.rows TableCount
                                     FROM syscolumns sc ,sysobjects,sysindexes,sysindexkeys 
                                     WHERE sysobjects.xtype = 'PK' 
                                           AND sysobjects.parent_obj = sc.id 
                                           AND sysindexes.id = sc.id 
                                           AND sysobjects.name = sysindexes.name AND sysindexkeys.id = sc.id 
                                           AND sysindexkeys.indid = sysindexes.indid 
                                           AND sc.colid = sysindexkeys.colid;";

            return _dbContext.Ado.SqlQuery<TableVo>(strSql); 
        }
        /// <summary>
        /// 获取表备注信息
        /// </summary>
        /// <returns></returns>
        private List<TableVo> GetTableRemarkList()
        {
            string strSql = @"SELECT  a.name AS TableName ,
                                CONVERT(NVARCHAR(100), ISNULL(g.[value], '-')) AS Remark
                        FROM    sys.tables a
                                LEFT JOIN sys.extended_properties g ON ( a.object_id = g.major_id
                                                                         AND g.minor_id = 0
                                                                       );";
            return _dbContext.Ado.SqlQuery<TableVo>(strSql);
        }

        /// <summary>
        /// 赋值表的主键、主键名称、记录数
        /// </summary>
        /// <param name="list"></param>
        private void SetTableDetail(List<TableVo> list)
        {
            List<TableVo> detailList = GetTableDetailList();
            List<TableVo> remarkList = GetTableRemarkList();
            foreach (TableVo table in list)
            {
                table.TableKey = string.Join(",", detailList.Where(p => p.Id == table.Id).Select(p => p.TableKey));
                var tableInfo = detailList.Where(p => p.TableName == table.TableName).FirstOrDefault();
                if (tableInfo != null)
                {
                    table.TableKeyName = tableInfo.TableKeyName;
                    table.TableCount = tableInfo.TableCount;
                    table.Remark = remarkList.Where(p => p.TableName == table.TableName).FirstOrDefault()?.Remark;
                }
            }
        }
        /// <summary>
        /// 数据表字段
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public DataTable GetTableFieldDataTable(string tableName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat(@"SELECT  
                                  TableColumn = rtrim(b.name),  
                                  TableIdentity = CASE WHEN h.id IS NOT NULL  THEN 'PK' ELSE '' END,  
                                  Datatype = type_name(b.xusertype)+CASE WHEN b.colstat&1=1 THEN '[ID(' + CONVERT(varchar, ident_seed(a.name))+','+CONVERT(varchar,ident_incr(a.name))+')]' ELSE '' END,  
                                  FieldLength = b.length,   
                                  IsNullable = CASE b.isnullable WHEN 0 THEN 'N' ELSE 'Y' END,   
                                  FieldDefault = ISNULL(e.text, ''),
                                  Remark = (SELECT ep.value FROM sys.columns sc LEFT JOIN sys.extended_properties ep ON ep.major_id = sc.object_id AND ep.minor_id = sc.column_id
										                    WHERE sc.object_id = a.id AND sc.name = b.name)
                            FROM sysobjects a, syscolumns b  
                            LEFT OUTER JOIN syscomments e ON b.cdefault = e.id  
                            LEFT OUTER JOIN (Select g.id, g.colid FROM sysindexes f, sysindexkeys g Where (f.id=g.id)AND(f.indid=g.indid)AND(f.indid>0)AND(f.indid<255)AND(f.status&2048)<>0) h ON (b.id=h.id)AND(b.colid=h.colid)  
                            Where (a.id=b.id)AND(a.id=object_id('{0}'))   
                                  ORDER BY b.colid", tableName);
            return _dbContext.Ado.GetDataTable(strSql.ToString());
        }

        /// <summary>
        /// 数据表字段
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public List<TableFieldInfo> GetTableFieldList(string tableName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat(@"SELECT  
                                  TableColumn = rtrim(b.name),  
                                  TableIdentity = CASE WHEN h.id IS NOT NULL  THEN 'PK' ELSE '' END,  
                                  Datatype = type_name(b.xusertype)+CASE WHEN b.colstat&1=1 THEN '[ID(' + CONVERT(varchar, ident_seed(a.name))+','+CONVERT(varchar,ident_incr(a.name))+')]' ELSE '' END,  
                                  FieldLength = b.length,   
                                  IsNullable = CASE b.isnullable WHEN 0 THEN 'N' ELSE 'Y' END,   
                                  FieldDefault = ISNULL(e.text, ''),
                                  Remark = (SELECT ep.value FROM sys.columns sc LEFT JOIN sys.extended_properties ep ON ep.major_id = sc.object_id AND ep.minor_id = sc.column_id
										                    WHERE sc.object_id = a.id AND sc.name = b.name)
                            FROM sysobjects a, syscolumns b  
                            LEFT OUTER JOIN syscomments e ON b.cdefault = e.id  
                            LEFT OUTER JOIN (Select g.id, g.colid FROM sysindexes f, sysindexkeys g Where (f.id=g.id)AND(f.indid=g.indid)AND(f.indid>0)AND(f.indid<255)AND(f.status&2048)<>0) h ON (b.id=h.id)AND(b.colid=h.colid)  
                            Where (a.id=b.id)AND(a.id=object_id('{0}'))   
                                  ORDER BY b.colid", tableName);
            return _dbContext.Ado.SqlQuery<TableFieldInfo>(strSql.ToString());
        }

        #endregion

        #region 分页数据

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="param"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public ActionResult GetPageListJson(BaseSearchParam param, Pagination pagination)
        {
            int totalCount = 0;
            List<TableVo> tables = _dbContext.SqlQueryable<TableVo>("SELECT id Id,name TableName,crdate CreateDate FROM sysobjects WHERE xtype = 'u' and name!='sysdiagrams'")
                             .WhereIF(!param.KeyWord.IsEmpty(), x => x.TableName == param.KeyWord.Trim())
                             .OrderBy(x => x.TableName)
                             .ToPageList(pagination.PageIndex, pagination.PageSize, ref totalCount);
            SetTableDetail(tables);
            return Content(DataResult<List<TableVo>>.PageResult(tables, totalCount).ToJson());
        }

        #endregion

        #region 简单生成 

        [HttpPost]
        public ActionResult CodePreviewJson(BaseConfigModel baseConfig)
        {
            DataTable dt = GetTableFieldDataTable(baseConfig.TableName);

            #region 构建Entity

            StringBuilder entity = new StringBuilder();
            entity.AppendLine("using SqlSugar;");
            entity.AppendLine("using System;");
            entity.AppendLine();
            entity.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.Data");
            entity.AppendLine("{");
            entity.AppendLine("    /// <summary>");
            entity.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            entity.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "实体类");
            entity.AppendLine("    /// </summary>");
            entity.AppendLine("    [SugarTable(\"" + baseConfig.TableName + "\")]");
            entity.AppendLine("    public class " + baseConfig.FileConfig.EntityName + " : BaseEntity");
            entity.AppendLine("    {");
            string entityColumn = string.Empty;
            string entityRemark = string.Empty;
            string datatype = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                entityColumn = dr["TableColumn"].ToString();
                if (entityColumn == "Id") continue;
                entityRemark = dr["Remark"].ToString();
                datatype = dr["Datatype"].ToString();
                datatype = TableMappingHelper.GetPropertyDatatype(datatype);
                entity.AppendLine("        /// <summary>");
                entity.AppendLine("        /// " + entityRemark);
                entity.AppendLine("        /// </summary>");
                entity.AppendLine("        public " + datatype + " " + entityColumn + " { get; set; }");
            }
            entity.AppendLine("    }");
            entity.AppendLine("}");
            string codeEntity = entity.ToString();

            #endregion

            #region 构建Dto

            StringBuilder dto = new StringBuilder();
            dto.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.Data");
            dto.AppendLine("{");
            dto.AppendLine("    /// <summary>");
            dto.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            dto.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "参数类");
            dto.AppendLine("    /// </summary>");
            dto.AppendLine($"    public class {baseConfig.FileConfig.EntityName}Dto");
            dto.AppendLine("    {");
            dto.AppendLine("        /// <summary>");
            dto.AppendLine("        /// 数据主键");
            dto.AppendLine("        /// </summary>");
            dto.AppendLine("        public int? Id { get; set; }"); 
            dto.AppendLine("    }");
            dto.AppendLine("}");
            string codeParam = dto.ToString();

            #endregion

            #region 构建Controller

            StringBuilder controller = new StringBuilder();
            controller.AppendLine("using System;");
            controller.AppendLine("using System.Collections.Generic;");
            controller.AppendLine("using System.Web.Mvc;");
            controller.AppendLine("using Mapster;");
            controller.AppendLine($"using {baseConfig.FileConfig.NameSpace}.Data;");
            controller.AppendLine($"using {baseConfig.FileConfig.NameSpace}.Utility;");
            controller.AppendLine();
            controller.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.WebApp.Areas." + baseConfig.FileConfig.AreaName + ".Controllers");
            controller.AppendLine("{");
            controller.AppendLine("    /// <summary>");
            controller.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            controller.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "控制器类");
            controller.AppendLine("    /// </summary>");
            controller.AppendLine("    public class " + baseConfig.FileConfig.ControllerName + " :  BaseController");
            controller.AppendLine("    {");
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 获取分页列表");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine("        /// <param name=\"param\"></param>");
            controller.AppendLine("        /// <param name=\"pagination\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        public ActionResult GetPageListJson(BaseSearchParam param, Pagination pagination)");
            controller.AppendLine("        {");
            controller.AppendLine("           int totalCount=0;");
            controller.AppendLine($"           var datas=_dbContext.Queryable<{baseConfig.FileConfig.EntityName}>()");
            controller.AppendLine("                               .Where(x => !x.DeletedMark)");
            controller.AppendLine("                               /*.WhereIF(!param.KeyWord.IsEmpty(), x => x.Name.Contains(param.KeyWord.Trim()))*/");
            controller.AppendLine("                               .ToPageList(pagination.PageIndex, pagination.PageSize, ref totalCount);");
            controller.AppendLine($"           return Content(DataResult<List<{baseConfig.FileConfig.EntityName}>>.PageResult(datas, totalCount).ToJson());");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// Form表单");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine("        /// <param name=\"id\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        public ActionResult Form(int? id)");
            controller.AppendLine("        {");
            controller.AppendLine($"           {baseConfig.FileConfig.EntityName} entity = new {baseConfig.FileConfig.EntityName}();");
            controller.AppendLine("           if (id != null)");
            controller.AppendLine("           {");
            controller.AppendLine($"              entity = _dbContext.Queryable<{baseConfig.FileConfig.EntityName}>().InSingle(id);");
            controller.AppendLine("           }");
            controller.AppendLine($"          return View(entity);");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 表单保存");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine($"       /// <param name=\"{TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        [HttpPost]");
            controller.AppendLine($"        public ActionResult SaveForm({baseConfig.FileConfig.EntityName}Dto {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto)");
            controller.AppendLine("        {");
            controller.AppendLine("            try");
            controller.AppendLine("            {");
            controller.AppendLine($"               {baseConfig.FileConfig.EntityName} entity = new {baseConfig.FileConfig.EntityName}();");
            controller.AppendLine($"               if ({TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Id == null)");
            controller.AppendLine("               {");
            controller.AppendLine($"                   {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Adapt(entity);");
            controller.AppendLine($"                   entity.CreatedOn = DateTime.Now;");
            controller.AppendLine($"                   entity.CreatedBy = OperatorProvider.Provider.GetCurrent().Id;");
            controller.AppendLine($"                   _dbContext.Insertable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            controller.AppendLine($"                   return Json(DataResult.Success(\"新增成功\"));");
            controller.AppendLine("               }");
            controller.AppendLine("               else");
            controller.AppendLine("               {");
            controller.AppendLine($"                   entity= _dbContext.Queryable<{baseConfig.FileConfig.EntityName}>().InSingle({TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Id);");
            controller.AppendLine($"                   {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Adapt(entity);");
            controller.AppendLine($"                   entity.UpdatedOn = DateTime.Now;");
            controller.AppendLine($"                   entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;");
            controller.AppendLine($"                   _dbContext.Updateable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            controller.AppendLine($"                   return Json(DataResult.Success(\"编辑成功\"));");
            controller.AppendLine("               }");
            controller.AppendLine("            }");
            controller.AppendLine("            catch (Exception ex)");
            controller.AppendLine("            {");
            controller.AppendLine("               return Json(DataResult.Error($\"保存失败,失败原因:{ex.Message}\"));");
            controller.AppendLine("            }");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 数据删除");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine($"       /// <param name=\"id\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        [HttpPost]");
            controller.AppendLine($"        public ActionResult DeleteData(int id)");
            controller.AppendLine("        {");
            controller.AppendLine("            try");
            controller.AppendLine("            {");
            controller.AppendLine($"               {baseConfig.FileConfig.EntityName} entity= _dbContext.Queryable<{baseConfig.FileConfig.EntityName}>().InSingle(id);");
            controller.AppendLine($"               entity.DeletedMark = true;");
            controller.AppendLine($"               entity.UpdatedOn = DateTime.Now;");
            controller.AppendLine($"               entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;");
            controller.AppendLine($"               _dbContext.Updateable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            controller.AppendLine("               return Json(DataResult.Success(\"删除成功\"));");
            controller.AppendLine("            }");
            controller.AppendLine("            catch (Exception ex)");
            controller.AppendLine("            {");
            controller.AppendLine("               return Json(DataResult.Error($\"删除失败,失败原因:{ex.Message}\"));");
            controller.AppendLine("            }");
            controller.AppendLine("        }");
            controller.AppendLine("    }");
            controller.AppendLine("}");
            string codeController = controller.ToString();

            #endregion

            #region 构建Index

            StringBuilder index = new StringBuilder();
            index.AppendLine("@{");
            index.AppendLine("    ViewBag.Title = \"\";");
            index.AppendLine("    Layout = \"~/Views/Shared/_Index.cshtml\";");
            index.AppendLine(" }");
            index.AppendLine("<section class=\"content\">");
            index.AppendLine("    <div class=\"row\">");
            index.AppendLine("         <div class=\"col-xs-12\">");
            index.AppendLine("              <div class=\"box box-info\">");
            index.AppendLine("                   <div class=\"box-body\">");
            index.AppendLine("                        <div class=\"table-responsive\">");
            index.AppendLine("                             <div class=\"btn-group-sm\" id=\"toolbar\" role=\"group\">");
            index.AppendLine("                                  <a id=\"btnAdd\" authorize =\"yes\" class=\"btn btn-success\" onclick =\"showForm('')\" ><i class=\"fa fa-plus\" ></i> 新增</a>");
            index.AppendLine("                                  <div class=\"col-sm-3 pull-right\">");
            index.AppendLine("                                       <div class=\"input-group input-group-sm\" >");
            index.AppendLine("                                            <input type=\"text\" id =\"keyWord\" col =\"KeyWord\" class=\"form-control\" placeholder =\"请输入关键字查询\" />");
            index.AppendLine("                                            <div class=\"input-group-btn\" >");
            index.AppendLine("                                                 <button type=\"button\" class=\"btn btn-primary\" onclick =\"searchGrid()\" ><i class=\"fa fa-search\" ></i></button>");
            index.AppendLine("                                            </div>");
            index.AppendLine("                                       </div>");
            index.AppendLine("                                  </div>");
            index.AppendLine("                             </div>");
            index.AppendLine("                             <table id=\"gridTable\" class=\"table table-hover table-striped text-nowrap\">");
            index.AppendLine("                             </table>");
            index.AppendLine("                        </div>");
            index.AppendLine("                   </div>");
            index.AppendLine("              </div>");
            index.AppendLine("         </div>");
            index.AppendLine("    </div>");
            index.AppendLine("</section>");
            index.AppendLine("");
            index.AppendLine("<script type=\"text/javascript\">");
            index.AppendLine("    $(function () {");
            index.AppendLine("        initGrid();");
            index.AppendLine("    });");
            index.AppendLine("");
            index.AppendLine("    function initGrid() {");
            index.AppendLine("        $('#gridTable').frameTable({");
            index.AppendLine("            url: '@Url.Action(\"GetPageListJson\", \"" + baseConfig.FileConfig.ClassPrefix + "\")',");
            index.AppendLine("            columns: ["); 
            index.AppendLine("                 { field: 'Id', title: 'Id', visible: false },");
            string indexColumn = string.Empty;
            string indexRemark = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                indexColumn = dr["TableColumn"].ToString();
                if (BaseField.BaseFieldList.Where(p => p == indexColumn).Any())
                {
                    continue;
                }
                indexRemark = dr["Remark"].ToString();
                index.AppendLine("                 { field: '" + indexColumn + "', title: '" + indexRemark + "', halign: \"center\", align: \"center\" },");
            }
            index.AppendLine("                 {");
            index.AppendLine("                     title: '操作',");
            index.AppendLine("                     align: 'center',");
            index.AppendLine("                     formatter: function (value, row, index) {");
            index.AppendLine("                         var actions = [];");
            index.AppendLine("                         actions.push('<a href=\"javascript:void(0);\" authorize=\"yes\" id=\"btnEdit\" class=\"btn btn-primary btn-xs\" onclick=\"showForm(\\'' + row.Id + '\\')\"><i class=\"fa fa-edit\"></i> 编辑</a> ');");
            index.AppendLine("                         actions.push('<a href=\"javascript:void(0);\" authorize=\"yes\" id=\"btnDelete\" class=\"btn btn-danger btn-xs\" onclick=\"deleteData(\\'' + row.Id + '\\')\"><i class=\"fa fa-trash-o\"></i> 删除</a>'); ");
            index.AppendLine("                         return actions.join('');");
            index.AppendLine("                     }");
            index.AppendLine("                 }");
            index.AppendLine("            ],");
            index.AppendLine("            queryParams: function (params) {");
            index.AppendLine("                 var pagination = $('#gridTable').frameTable('getPagination', params);");
            index.AppendLine("                 var queryString = $('#toolbar').getWebControls(pagination);");
            index.AppendLine("                 return queryString;");
            index.AppendLine("            }");
            index.AppendLine("        });");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function searchGrid() {");
            index.AppendLine("        $('#gridTable').frameTable('search');");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function showForm(id) {");
            index.AppendLine("        frame.openDialog({");
            index.AppendLine("            title: !!id ? '编辑' : '添加',");
            index.AppendLine("            content: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/Form\")' + '?id=\' + id,");
            index.AppendLine("            width: '768px',");
            index.AppendLine("            height: '550px',");
            index.AppendLine("            callback: function (index, layero) {");
            index.AppendLine("                var iframeWin = window[layero.find('iframe')[0]['name']];");
            index.AppendLine("                iframeWin.saveForm(index);");
            index.AppendLine("            }");
            index.AppendLine("        });");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function deleteData(id) {");
            index.AppendLine("            frame.confirm(\"确定要删除该数据吗？\", function () {");
            index.AppendLine("                frame.ajax({");
            index.AppendLine("                    url: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/DeleteData\")' + '?id=' + id,");
            index.AppendLine("                    type: 'post',");
            index.AppendLine("                    success: function (obj) {");
            index.AppendLine("                         if (obj.success) {");
            index.AppendLine("                            frame.msgSuccess(obj.message);");
            index.AppendLine("                            searchGrid();");
            index.AppendLine("                        }");
            index.AppendLine("                        else {");
            index.AppendLine("                            frame.msgError(obj.message);");
            index.AppendLine("                        }");
            index.AppendLine("                    }");
            index.AppendLine("                });");
            index.AppendLine("            });");
            index.AppendLine("    }");
            index.AppendLine("</script>");
            string codeIndex = index.ToString();

            #endregion

            #region 构建Form

            StringBuilder form = new StringBuilder();
            form.AppendLine("@{");
            form.AppendLine("    ViewBag.Title = \"\";");
            form.AppendLine("    Layout = \"~/Views/Shared/_Form.cshtml\";");
            form.AppendLine(" }");
            form.AppendLine($"@model {baseConfig.FileConfig.NameSpace}.Data.{baseConfig.FileConfig.EntityName} ");
            form.AppendLine("");
            form.AppendLine("<form id=\"form\" class=\"form-horizontal m\" role=\"form\" > ");
            string field = string.Empty;
            string fieldLower = string.Empty;
            string formRemark = string.Empty;
            switch (baseConfig.FileConfig.ShowMode)
            {
                case 1:
                    foreach (DataRow dr in dt.Rows)
                    {
                        field = dr["TableColumn"].ToString();
                        fieldLower = TableMappingHelper.FirstLetterLowercase(field);
                        if (BaseField.BaseFieldList.Where(p => p == field).Any())
                        {
                            continue;
                        }
                        formRemark = dr["Remark"].ToString();
                        form.AppendLine("        <div class=\"form-group\">");
                        form.AppendLine("            <label class=\"col-sm-3 control-label \">" + formRemark + "<span class=\"text-red\"> *</span></label>");
                        form.AppendLine("            <div class=\"col-sm-9 form-valid\">");
                        form.AppendLine("               @Html.TextBoxFor(model => model." + field + ", new { @class = \"form-control required\", @placeholder = \"请输入" + formRemark + "\", @formRules = \"isNonEmpty\", @formError = \"必填\" })");
                        form.AppendLine("            </div>");
                        form.AppendLine("        </div>");
                    }
                    break;

                case 2:
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        field = dt.Rows[i]["TableColumn"].ToString();
                        fieldLower = TableMappingHelper.FirstLetterLowercase(field);
                        if (BaseField.BaseFieldList.Where(p => p == field).Any())
                        {
                            continue;
                        }
                        formRemark = dt.Rows[i]["Remark"].ToString();
                        if (i % 2 == 0)
                        {
                            form.AppendLine("        <div class=\"form-group\">");
                        }
                        form.AppendLine("            <label class=\"control-label col-xs-12 col-sm-2\">" + formRemark + "<span class=\"text-red\"> *</span></label>");
                        form.AppendLine("            <div class=\"col-xs-12 col-sm-4 form-valid\">");
                        form.AppendLine("               @Html.TextBoxFor(model => model." + field + ", new { @class = \"form-control required\", @placeholder = \"请输入" + formRemark + "\", @formRules = \"isNonEmpty\", @formError = \"必填\" })");
                        form.AppendLine("            </div>");
                        if (i % 2 == 1)
                        {
                            form.AppendLine("        </div>");
                        }
                    }
                    break;
            }
            form.AppendLine("</form>");
            form.AppendLine("");
            form.AppendLine("<script type=\"text/javascript\">");
            form.AppendLine("    function saveForm() {");
            form.AppendLine("         if ($('form').validate('submitValidate')) {");
            form.AppendLine("            frame.ajax({");
            form.AppendLine("                url: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/SaveForm\")',");
            form.AppendLine("                type: 'post',");
            form.AppendLine("                data: $('form').formSerialize(),");
            form.AppendLine("                success: function (obj) {");
            form.AppendLine("                    if (obj.success) {");
            form.AppendLine("                        frame.msgSuccess(obj.message);");
            form.AppendLine("                        parent.searchGrid();");
            form.AppendLine("                        frame.closeDialog();");
            form.AppendLine("                    }");
            form.AppendLine("                    else {");
            form.AppendLine("                        frame.msgError(obj.message);");
            form.AppendLine("                    }");
            form.AppendLine("                }");
            form.AppendLine("            });");
            form.AppendLine("        }");
            form.AppendLine("    }");
            form.AppendLine("</script>");
            string codeForm = form.ToString();

            #endregion

            #region 构建Menu

            StringBuilder menu = new StringBuilder();
            menu.AppendLine();
            menu.AppendLine("  菜单路径:" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/" + baseConfig.FileConfig.PageIndexName);
            menu.AppendLine();
            string modulePrefix = baseConfig.FileConfig.AreaName.ToLower();
            string classPrefix = baseConfig.FileConfig.ClassPrefix.ToLower();
            List<KeyValue> list = new List<KeyValue>();
            list.Add(new KeyValue { Key = "btnSearch", Value = "search", Description = "搜索" });
            list.Add(new KeyValue { Key = "btnAdd", Value = "add", Description = "新增" });
            list.Add(new KeyValue { Key = "btnEdit", Value = "edit", Description = "修改" });
            list.Add(new KeyValue { Key = "btnDelete", Value = "delete", Description = "删除" });
            foreach (var item in list)
            {
                menu.AppendLine("  按钮" + item.Description + "权限：" + string.Format("{0}:{1}:{2}", modulePrefix, classPrefix, item.Value));
            }
            menu.AppendLine();
            string codeMenu = menu.ToString();

            #endregion

            var json = new
            {
                CodeEntity = HttpUtility.HtmlEncode(codeEntity),
                CodeParam= HttpUtility.HtmlEncode(codeParam),
                CodeController = HttpUtility.HtmlEncode(codeController),
                CodeIndex = HttpUtility.HtmlEncode(codeIndex),
                CodeForm = HttpUtility.HtmlEncode(codeForm),
                CodeMenu = HttpUtility.HtmlEncode(codeMenu)
            };
            return Content(DataResult<dynamic>.Success(json).ToJson());
        }

        [HttpPost]
        public ActionResult CodeGenerateJson(BaseConfigModel baseConfig, string code)
        {
            List<KeyValue> result = new List<KeyValue>();
            JObject param = HttpUtility.UrlDecode(code).ToJObject();

            #region 实体类
            if (!string.IsNullOrEmpty(param["CodeEntity"].ParseToString()))
            {
                string codeEntity = HttpUtility.HtmlDecode(param["CodeEntity"].ToString());
                string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{baseConfig.FileConfig.NameSpace}.Entity", "Entity", baseConfig.FileConfig.EntityName + ".cs");
                if (!System.IO.File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeEntity);
                }
                result.Add(new KeyValue { Key = "实体类", Value = codePath });
            }
            #endregion

            #region 参数类

            if (!string.IsNullOrEmpty(param["CodeParam"].ParseToString()))
            {
                string codeEntity = HttpUtility.HtmlDecode(param["CodeParam"].ToString());
                string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{baseConfig.FileConfig.NameSpace}.Entity", "Dto", baseConfig.FileConfig.EntityName + "Dto.cs");
                if (!System.IO.File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeEntity);
                }
                result.Add(new KeyValue { Key = "参数类", Value = codePath });
            }

            #endregion

            #region 控制器
            if (!param["CodeController"].IsEmpty())
            {
                string codeController = HttpUtility.HtmlDecode(param["CodeController"].ToString());
                string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{baseConfig.FileConfig.NameSpace}.Web", "Controllers", baseConfig.FileConfig.ControllerName + ".cs");
                if (!System.IO.File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeController);
                }
                result.Add(new KeyValue { Key = "控制器", Value = codePath });
            }
            #endregion

            #region 列表页
            if (!param["CodeIndex"].IsEmpty())
            {
                string codeIndex = HttpUtility.HtmlDecode(param["CodeIndex"].ToString());
                string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{baseConfig.FileConfig.NameSpace}.Web", "Views", baseConfig.FileConfig.ClassPrefix, baseConfig.FileConfig.PageIndexName + ".cshtml");
                if (!System.IO.File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeIndex);
                }
                result.Add(new KeyValue { Key = "列表页", Value = codePath });
            }
            #endregion

            #region 表单页
            if (!param["CodeForm"].IsEmpty())
            {
                string codeSave = HttpUtility.HtmlDecode(param["CodeForm"].ToString());
                string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{baseConfig.FileConfig.NameSpace}.Web", "Views", baseConfig.FileConfig.ClassPrefix, baseConfig.FileConfig.PageFormName + ".cshtml");
                if (!System.IO.File.Exists(codePath))
                {
                    FileHelper.CreateFile(codePath, codeSave);
                }
                result.Add(new KeyValue { Key = "表单页", Value = codePath });
            }
            #endregion

            return Content(DataResult<List<KeyValue>>.Success(result).ToJson());
        }

        #endregion

        #region 复杂生成

        /// <summary>
        /// 复杂生成
        /// </summary>
        /// <returns></returns>
        public ActionResult FormComplex()
        {
            return View();
        }

        /// <summary>
        /// 数据表字段
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public ActionResult GetTableFieldListJson(string tableName)
        {
            DataResult<List<TableFieldInfo>> obj = new DataResult<List<TableFieldInfo>>();
            List<TableFieldInfo> dataList = GetTableFieldList(tableName);
            return Content(DataResult<List<TableFieldInfo>>.Success(dataList).ToJson());
        }

        /// <summary>
        /// 代码预览
        /// </summary>
        /// <param name="baseConfig"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CodePreviewComplexJson(BaseConfigModel baseConfig)
        {
            DataTable dt = DataTableHelper.ListToDataTable(baseConfig.tableField);
            List<TableFieldModel> FieldList = DataTableHelper.DataTableToList<TableFieldModel>(dt);

            #region 构建Entity

            StringBuilder entity = new StringBuilder();
            entity.AppendLine("using SqlSugar;");
            entity.AppendLine("using System;");
            entity.AppendLine();
            entity.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.Data");
            entity.AppendLine("{");
            entity.AppendLine("    /// <summary>");
            entity.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            entity.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "实体类");
            entity.AppendLine("    /// </summary>");
            entity.AppendLine("    [SugarTable(\"" + baseConfig.TableName + "\")]");
            entity.AppendLine("    public class " + baseConfig.FileConfig.EntityName + " : BaseEntity");
            entity.AppendLine("    {");
            string entityColumn = string.Empty;
            string entityRemark = string.Empty;
            string datatype = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                entityColumn = dr["TableColumn"].ToString();
                if (entityColumn == "Id") continue;
                entityRemark = dr["Remark"].ToString();
                datatype = dr["Datatype"].ToString();
                datatype = TableMappingHelper.GetPropertyDatatype(datatype);
                entity.AppendLine("        /// <summary>");
                entity.AppendLine("        /// " + entityRemark);
                entity.AppendLine("        /// </summary>");
                entity.AppendLine("        public " + datatype + " " + entityColumn + " { get; set; }");
            }
            entity.AppendLine("    }");
            entity.AppendLine("}");
            string codeEntity = entity.ToString();

            #endregion 

            #region 构建Dto

            StringBuilder dto = new StringBuilder();
            dto.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.Data");
            dto.AppendLine("{");
            dto.AppendLine("    /// <summary>");
            dto.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            dto.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "参数类");
            dto.AppendLine("    /// </summary>");
            dto.AppendLine($"    public class {baseConfig.FileConfig.EntityName}Dto");
            dto.AppendLine("    {");
            entity.AppendLine("      /// <summary>");
            entity.AppendLine("      /// 数据主键" );
            entity.AppendLine("      /// </summary>");
            dto.AppendLine("         public int? Id { get; set; }");
            string dtoColumn = string.Empty;
            string dtoRemark = string.Empty;
            string dtoDataType = string.Empty;
            foreach (var item in FieldList.Where(x => x.IsEdit == true))
            {
                dtoColumn = item.TableColumn;
                if (BaseField.BaseFieldList.Where(p => p == dtoColumn).Any())
                {
                    continue;
                }
                dtoRemark = item.Remark;
                dtoDataType = item.Datatype;
                dtoDataType = TableMappingHelper.GetPropertyDatatype(dtoDataType);
                dto.AppendLine("        /// <summary>");
                dto.AppendLine("        /// " + dtoRemark);
                dto.AppendLine("        /// </summary>");
                dto.AppendLine("        public " + dtoDataType + " " + dtoColumn + " { get; set; }");
            }
            dto.AppendLine("    }");
            dto.AppendLine("}");
            string codeParam = dto.ToString();

            #endregion

            #region 构建Controller

            StringBuilder controller = new StringBuilder();
            controller.AppendLine("using System;");
            controller.AppendLine("using System.Collections.Generic;");
            controller.AppendLine("using System.Web.Mvc;");
            controller.AppendLine("using Mapster;");
            controller.AppendLine($"using {baseConfig.FileConfig.NameSpace}.Data;");
            controller.AppendLine($"using {baseConfig.FileConfig.NameSpace}.Utility;");
            controller.AppendLine();
            controller.AppendLine($"namespace {baseConfig.FileConfig.NameSpace}.WebApp.Areas." + baseConfig.FileConfig.AreaName + ".Controllers");
            controller.AppendLine("{");
            controller.AppendLine("    /// <summary>");
            controller.AppendLine("    /// 日 期：" + baseConfig.FileConfig.CreateDate);
            controller.AppendLine("    /// 描 述：" + baseConfig.FileConfig.ClassDescription + "控制器类");
            controller.AppendLine("    /// </summary>");
            controller.AppendLine("    public class " + baseConfig.FileConfig.ControllerName + " :  BaseController<" + baseConfig.FileConfig.EntityName + ">");
            controller.AppendLine("    {");
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 获取分页列表");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine("        /// <param name=\"param\"></param>");
            controller.AppendLine("        /// <param name=\"pagination\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        public ActionResult GetPageListJson(BaseSearchParam param, Pagination pagination)");
            controller.AppendLine("        {");
            controller.AppendLine("           int totalCount=0;");
            controller.AppendLine($"           var datas=_dbContext.Queryable<{baseConfig.FileConfig.EntityName}>()");
            if (FieldList.Any(x => x.TableColumn == "DeletedMark"))
            {
                controller.AppendLine("                               .Where(x => !x.DeletedMark)");
            }
            controller.AppendLine("                               /*.WhereIF(!param.KeyWord.IsEmpty(), x => x.Name.Contains(param.KeyWord.Trim()))*/");
            controller.AppendLine("                               .ToPageList(pagination.PageIndex, pagination.PageSize, ref totalCount);");
            controller.AppendLine($"           return Content(DataResult<List<{baseConfig.FileConfig.EntityName}>>.PageResult(datas, totalCount).ToJson());");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// Form表单");
            controller.AppendLine("        /// </summary>"); 
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        public ActionResult Form()");
            controller.AppendLine("        {"); 
            controller.AppendLine($"          return View();");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 表单保存");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine($"       /// <param name=\"{TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        [HttpPost]");
            controller.AppendLine($"       public ActionResult SaveForm({baseConfig.FileConfig.EntityName}Dto {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto)");
            controller.AppendLine("        {");
            controller.AppendLine("            try");
            controller.AppendLine("            {");
            controller.AppendLine($"               {baseConfig.FileConfig.EntityName} entity = new {baseConfig.FileConfig.EntityName}();");
            controller.AppendLine($"               if ({TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Id == null)");
            controller.AppendLine("               {");
            controller.AppendLine($"                   {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Adapt(entity);");
            controller.AppendLine($"                   entity.CreatedOn = DateTime.Now;");
            controller.AppendLine($"                   entity.CreatedBy = OperatorProvider.Provider.GetCurrent().Id;");
            controller.AppendLine($"                   _dbContext.Insertable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            controller.AppendLine($"                   return Json(DataResult.Success(\"新增成功\"));");
            controller.AppendLine("               }");
            controller.AppendLine("               else");
            controller.AppendLine("               {");
            controller.AppendLine($"                   entity= _dbContext.Queryable<{baseConfig.FileConfig.EntityName}>().InSingle({TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Id);");
            controller.AppendLine($"                   {TableMappingHelper.FirstLetterLowercase(baseConfig.FileConfig.EntityName)}Dto.Adapt(entity);");
            controller.AppendLine($"                   entity.UpdatedOn = DateTime.Now;");
            controller.AppendLine($"                   entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;");
            controller.AppendLine($"                   _dbContext.Updateable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            controller.AppendLine($"                   return Json(DataResult.Success(\"编辑成功\"));");
            controller.AppendLine("               }");
            controller.AppendLine("            }");
            controller.AppendLine("            catch (Exception ex)");
            controller.AppendLine("            {");
            controller.AppendLine("               return Json(DataResult.Error($\"保存失败,失败原因:{ex.Message}\"));");
            controller.AppendLine("            }");
            controller.AppendLine("        }");
            controller.AppendLine();
            controller.AppendLine("        /// <summary>");
            controller.AppendLine("        /// 数据删除");
            controller.AppendLine("        /// </summary>");
            controller.AppendLine($"       /// <param name=\"id\"></param>");
            controller.AppendLine("        /// <returns></returns>");
            controller.AppendLine("        [HttpPost]");
            controller.AppendLine($"       public ActionResult DeleteData(int id)");
            controller.AppendLine("        {");
            controller.AppendLine("            try");
            controller.AppendLine("            {"); 
            if (FieldList.Any(x => x.TableColumn == "DeletedMark"))
            {
                controller.AppendLine($"              {baseConfig.FileConfig.EntityName} entity= _dbContext.Queryable<{baseConfig.FileConfig.EntityName}>().InSingle(id);");
                controller.AppendLine($"              entity.DeletedMark = true;");
                controller.AppendLine($"              entity.UpdatedOn = DateTime.Now;");
                controller.AppendLine($"              entity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;");
                controller.AppendLine($"              _dbContext.Updateable<{baseConfig.FileConfig.EntityName}>(entity).ExecuteCommand();");
            }
            else
            {
                controller.AppendLine($"              _dbContext.Deleteable<{baseConfig.FileConfig.EntityName}>().In(id).ExecuteCommand();");
            }
            controller.AppendLine("               return Json(DataResult.Success(\"删除成功\"));");
            controller.AppendLine("            }");
            controller.AppendLine("            catch (Exception ex)");
            controller.AppendLine("            {");
            controller.AppendLine("               return Json(DataResult.Error($\"删除失败,失败原因:{ex.Message}\"));");
            controller.AppendLine("            }");
            controller.AppendLine("        }");
            controller.AppendLine("    }");
            controller.AppendLine("}");
            string codeController = controller.ToString();

            #endregion

            #region 构建Index

            StringBuilder index = new StringBuilder();
            index.AppendLine("@{");
            index.AppendLine("    ViewBag.Title = \"\";");
            index.AppendLine("    Layout = \"~/Views/Shared/_Index.cshtml\";");
            index.AppendLine(" }");
            index.AppendLine("<section class=\"content\">");
            index.AppendLine("    <div class=\"row\">");
            index.AppendLine("         <div class=\"col-xs-12\">");
            index.AppendLine("              <div class=\"box box-info\">");
            index.AppendLine("                   <div class=\"box-body\">");
            index.AppendLine("                        <div class=\"table-responsive\">");
            index.AppendLine("                             <div class=\"btn-group-sm\" id=\"toolbar\" role=\"group\">");
            index.AppendLine("                                  <a id=\"btnAdd\" authorize =\"yes\" class=\"btn btn-success\" onclick =\"showForm('')\" ><i class=\"fa fa-plus\" ></i> 新增</a>");
            index.AppendLine("                                  <div class=\"col-sm-3 pull-right\">");
            index.AppendLine("                                       <div class=\"input-group input-group-sm\" >");
            index.AppendLine("                                            <input type=\"text\" id =\"keyWord\" col =\"KeyWord\" class=\"form-control\" placeholder =\"请输入关键字查询\" />");
            index.AppendLine("                                            <div class=\"input-group-btn\" >");
            index.AppendLine("                                                 <button type=\"button\" class=\"btn btn-primary\" onclick =\"searchGrid()\" ><i class=\"fa fa-search\" ></i></button>");
            index.AppendLine("                                            </div>");
            index.AppendLine("                                       </div>");
            index.AppendLine("                                  </div>");
            index.AppendLine("                             </div>");
            index.AppendLine("                             <table id=\"gridTable\" class=\"table table-hover table-striped text-nowrap\">");
            index.AppendLine("                             </table>");
            index.AppendLine("                        </div>");
            index.AppendLine("                   </div>");
            index.AppendLine("              </div>");
            index.AppendLine("         </div>");
            index.AppendLine("    </div>");
            index.AppendLine("</section>");
            index.AppendLine("");
            index.AppendLine("<script type=\"text/javascript\">");
            index.AppendLine("    $(function () {");
            index.AppendLine("        initGrid();");
            index.AppendLine("    });");
            index.AppendLine("");
            index.AppendLine("    function initGrid() {");
            index.AppendLine("        $('#gridTable').frameTable({");
            index.AppendLine("            url: '@Url.Action(\"GetPageListJson\", \"" + baseConfig.FileConfig.ClassPrefix + "\")',");
            index.AppendLine("            columns: ["); 
            index.AppendLine("                 { field: 'Id', title: 'Id', visible: false },");
            string indexColumn = string.Empty;
            string indexRemark = string.Empty;
            //勾选了在列表显示的字段
            foreach (var item in FieldList.Where(x => x.IsList == true))
            {
                indexColumn = item.TableColumn;
                if (BaseField.BaseFieldList.Where(p => p == indexColumn).Any())
                {
                    continue;
                }
                indexRemark = item.Remark;
                if (indexColumn == "EnabledMark")
                {
                    index.AppendLine("                 { field: '" + indexColumn + "', title: '" + indexRemark + "', halign: \"center\", align: \"center\",");
                    index.AppendLine("                   formatter: function (value, row, index) {");
                    index.AppendLine("                       if (!!row.EnabledMark) {");
                    index.AppendLine("                           return '<i class=\"fa fa-toggle-on text-info fa-2x\"></i> ';");
                    index.AppendLine("                       }else{");
                    index.AppendLine("                           return '<i class=\"fa fa-toggle-off text-info fa-2x\"></i> ';");
                    index.AppendLine("                       }");
                    index.AppendLine("                   }");
                    index.AppendLine("                 },");
                }
                else
                {
                    index.AppendLine("                 { field: '" + indexColumn + "', title: '" + indexRemark + "', halign: \"center\", align: \"center\" },");
                }
            } 
            index.AppendLine("                 {");
            index.AppendLine("                     title: '操作',");
            index.AppendLine("                     align: 'center',");
            index.AppendLine("                     formatter: function (value, row, index) {");
            index.AppendLine("                         var actions = [];");
            index.AppendLine("                         actions.push('<a href=\"javascript:void(0);\" authorize=\"yes\" id=\"btnEdit\" class=\"btn btn-primary btn-xs\" onclick=\"showForm(\\'' + row.Id + '\\')\"><i class=\"fa fa-edit\"></i> 编辑</a> ');");
            index.AppendLine("                         actions.push('<a href=\"javascript:void(0);\" authorize=\"yes\" id=\"btnDelete\" class=\"btn btn-danger btn-xs\" onclick=\"deleteData(\\'' + row.Id + '\\')\"><i class=\"fa fa-trash-o\"></i> 删除</a>'); ");
            index.AppendLine("                         return actions.join('');");
            index.AppendLine("                     }");
            index.AppendLine("                 }");
            index.AppendLine("            ],");
            index.AppendLine("            queryParams: function (params) {");
            index.AppendLine("                 var pagination = $('#gridTable').frameTable('getPagination', params);");
            index.AppendLine("                 var queryString = $('#toolbar').getWebControls(pagination);");
            index.AppendLine("                 return queryString;");
            index.AppendLine("            }");
            index.AppendLine("        });");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function searchGrid() {");
            index.AppendLine("        $('#gridTable').frameTable('search');");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function showForm(id) {");
            index.AppendLine("        frame.openDialog({");
            index.AppendLine("            title: !!id ? '编辑" + baseConfig.FileConfig.ClassDescription + "': '添加" + baseConfig.FileConfig.ClassDescription + "', ");
            index.AppendLine("            content: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/Form\")' + '?id=\' + id,");
            index.AppendLine("            width: '768px',");
            index.AppendLine("            height: '550px',");
            index.AppendLine("            callback: function (index, layero) {");
            index.AppendLine("                var iframeWin = window[layero.find('iframe')[0]['name']];");
            index.AppendLine("                iframeWin.saveForm(index);");
            index.AppendLine("            }");
            index.AppendLine("        });");
            index.AppendLine("    }");
            index.AppendLine("");
            index.AppendLine("    function deleteData(id) {");
            index.AppendLine("            frame.confirm(\"确定要删除该数据吗？\", function () {");
            index.AppendLine("                frame.ajax({");
            index.AppendLine("                    url: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/DeleteData\")' + '?id=' + id,");
            index.AppendLine("                    type: 'post',");
            index.AppendLine("                    success: function (obj) {");
            index.AppendLine("                         if (obj.success) {");
            index.AppendLine("                            frame.msgSuccess(obj.message);");
            index.AppendLine("                            searchGrid();");
            index.AppendLine("                        }");
            index.AppendLine("                        else {");
            index.AppendLine("                            frame.msgError(obj.message);");
            index.AppendLine("                        }");
            index.AppendLine("                    }");
            index.AppendLine("                });");
            index.AppendLine("            });");
            index.AppendLine("    }");
            index.AppendLine("</script>");
            string codeIndex = index.ToString();

            #endregion

            #region 构建Form

            StringBuilder form = new StringBuilder();
            form.AppendLine("@{");
            form.AppendLine("    ViewBag.Title = \"\";");
            form.AppendLine("    Layout = \"~/Views/Shared/_Form.cshtml\";");
            form.AppendLine(" }");
            form.AppendLine("");
            form.AppendLine("<form id=\"form\" class=\"form-horizontal m\" role=\"form\" > ");
            string field = string.Empty;
            string fieldLower = string.Empty;
            string formRemark = string.Empty; 
            switch (baseConfig.FileConfig.ShowMode)
            {
                case 1:
                    foreach (var item in FieldList.Where(x => x.IsEdit == true))
                    {
                        field = item.TableColumn;
                        fieldLower = TableMappingHelper.FirstLetterLowercase(field);
                        if (BaseField.BaseFieldList.Where(p => p == field).Any())
                        {
                            continue;
                        }
                        formRemark = item.Remark;
                        form.AppendLine("        <div class=\"form-group\">");
                        form.AppendLine("            <label class=\"col-sm-3 control-label \">" + formRemark + (item.IsRequire ? "<span class=\"text-red\"> *</span>" : string.Empty) + "</label>");
                        switch (item.FormType)
                        {
                            //文本框
                            case "input":
                                form.AppendLine("            <div class=\"col-sm-9\">");
                                form.AppendLine("                <input id=\"" + fieldLower + "\" name=\"" + field + "\" col=\"" + field + "\" type=\"text\" class=\"form-control " + (item.IsRequire ? "required" : string.Empty) + " \" placeholder=\"请输入" + formRemark + "\" />");
                                form.AppendLine("            </div>");
                                break;
                            //文本域
                            case "textarea":
                                form.AppendLine("            <div class=\"col-sm-9\">");
                                form.AppendLine("                <textarea id=\"" + fieldLower + "\" name=\"" + field + "\" col=\"" + field + "\" type=\"text\" class=\"form-control " + (item.IsRequire ? "required" : string.Empty) + "\" placeholder=\"请输入" + formRemark + "\" rows=\"2\" />");
                                form.AppendLine("            </div>");
                                break;
                            //下拉框
                            case "select":
                                form.AppendLine("            <span class=\"col-sm-9\"   id=\"" + fieldLower + "\" col=\"" + field + "\" ></span>");
                                break;
                            //单选框
                            case "radio":
                                form.AppendLine("            <div class=\"col-sm-9\" id=\"" + fieldLower + "\" col=\"" + field + "\" > ");
                                form.AppendLine("            </div> ");
                                break;
                            //复选框
                            case "checkbox":
                                form.AppendLine("            <div class=\"col-sm-9\" id=\"" + fieldLower + "\" col=\"" + field + "\" > ");
                                form.AppendLine("            </div> ");
                                break;
                            //日期控件
                            case "datetime":
                                form.AppendLine("            <div class=\"col-sm-9\" >> ");
                                form.AppendLine("                 <div class=\"input-group date\" id=\"" + fieldLower + "\">");
                                form.AppendLine("                      <input type=\"text\" class=\"form-control required\" placeholder=\"请输入" + formRemark + "\" col=\"" + field + "\" />");
                                form.AppendLine("                      <span class=\"input-group-addon\" > ");
                                form.AppendLine("                         <span class=\"glyphicon glyphicon-calendar\" ></span>");
                                form.AppendLine("                      </span> ");
                                form.AppendLine("                 </div> ");
                                form.AppendLine("            </div> ");
                                break;
                        }
                        form.AppendLine("        </div>");
                    }
                    break; 

                case 2:
                    var tempList = FieldList.Where(x => x.IsEdit == true).ToList();
                    for (int i = 0; i < tempList.Count(); i++)
                        {
                            field = tempList[i].TableColumn;
                            fieldLower = TableMappingHelper.FirstLetterLowercase(field);
                            if (BaseField.BaseFieldList.Where(p => p == field).Any())
                            {
                                continue;
                            }
                            formRemark = tempList[i].Remark;
                            if (i % 2 == 0)
                            {
                                form.AppendLine("        <div class=\"form-group\">");
                            }
                            form.AppendLine("            <label class=\"control-label col-xs-12 col-sm-2 \">" + formRemark + (tempList[i].IsRequire ? "<span class=\"text-red\"> *</span>" : string.Empty) + "</label>");
                            switch (tempList[i].FormType)
                            {
                                //文本框
                                case "input":
                                    form.AppendLine("            <div class=\"col-xs-12 col-sm-4\">");
                                    form.AppendLine("                <input id=\"" + fieldLower + "\" name=\"" + field + "\" col=\"" + field + "\" type=\"text\" class=\"form-control " + (tempList[i].IsRequire ? "required" : string.Empty) + "\" placeholder=\"请输入" + formRemark + "\" />");
                                    form.AppendLine("            </div>");
                                    break;
                                //文本域
                                case "textarea":
                                    form.AppendLine("            <div class=\"col-xs-12 col-sm-4\">");
                                    form.AppendLine("                <textarea id=\"" + fieldLower + "\" name=\"" + field + "\" col=\"" + field + "\" type=\"text\" class=\"form-control requi" + (tempList[i].IsRequire ? "required" : string.Empty) + "red\" placeholder=\"请输入" + formRemark + "\" rows=\"2\" />");
                                    form.AppendLine("            </div>");
                                    break;
                                //下拉框
                                case "select":
                                    form.AppendLine("            <span class=\"col-xs-12 col-sm-4\"   id=\"" + fieldLower + "\" col=\"" + field + "\" ></span>");
                                    break;
                                //单选框
                                case "radio":
                                    form.AppendLine("            <div class=\"col-xs-12 col-sm-4\" id=\"" + fieldLower + "\" col=\"" + field + "\" > ");
                                    form.AppendLine("            </div> ");
                                    break;
                                //复选框
                                case "checkbox":
                                    form.AppendLine("            <div class=\"col-xs-12 col-sm-4\" id=\"" + fieldLower + "\" col=\"" + field + "\" > ");
                                    form.AppendLine("            </div> ");
                                    break;
                                //日期控件
                                case "datetime":
                                    form.AppendLine("            <div class=\"col-xs-12 col-sm-4\" >> ");
                                    form.AppendLine("                 <div class=\"input-group date\" id=\"" + fieldLower + "\">");
                                    form.AppendLine("                      <input type=\"text\" class=\"form-control " + (tempList[i].IsRequire ? "required" : string.Empty) + "\" placeholder=\"请输入" + formRemark + "\" col=\"" + field + "\" />");
                                    form.AppendLine("                      <span class=\"input-group-addon\" > ");
                                    form.AppendLine("                         <span class=\"glyphicon glyphicon-calendar\" ></span>");
                                    form.AppendLine("                      </span> ");
                                    form.AppendLine("                 </div> ");
                                    form.AppendLine("            </div> ");
                                    break;
                            }
                            if (i % 2 == 1)
                            {
                                form.AppendLine("        </div>");
                            }
                        }
                    break;
            }
            form.AppendLine("</form>");
            form.AppendLine("");
            form.AppendLine("<script type=\"text/javascript\">");
            form.AppendLine("    var id = frame.request(\"id\");");
            form.AppendLine("    $(function () {");
            foreach (var item in FieldList)
            {
                field = item.TableColumn;
                fieldLower = TableMappingHelper.FirstLetterLowercase(field);
                if (BaseField.BaseFieldList.Where(p => p == field).Any())
                {
                    continue;
                } 
                if (item.FormType == "radio" && !item.BindDicCode.IsEmpty())
                {
                    form.AppendLine("        $(\"#" + fieldLower + "\").frameRadioBox({ url: \"/Common/GetDictionaryDetailByType?dicType=" + item.BindDicCode + "\", });");
                }
                if (item.FormType == "checkbox" && !item.BindDicCode.IsEmpty())
                {
                    form.AppendLine("        $(\"#" + fieldLower + "\").frameCheckBox({ url: \"/Common/GetDictionaryDetailByType?dicType=" + item.BindDicCode + "\", });");
                }
                if (item.FormType == "select" && !item.BindDicCode.IsEmpty())
                {
                    form.AppendLine("        $(\"#" + fieldLower + "\").frameComboBox({ url: \"/Common/GetDictionaryDetailByType?dicType=" + item.BindDicCode + "\"" + (item.IsRequire ? "," : string.Empty) + "");
                    if (item.IsRequire)
                    {
                        form.AppendLine("             isRequire: \"true\"");
                    }
                    form.AppendLine("        });");
                }
                if (item.FormType == "datetime")
                {
                    form.AppendLine("        $(\"#" + fieldLower + "\").datetimepicker({");
                    form.AppendLine("             format: 'YYYY-MM-DD',");
                    form.AppendLine("             showClear: true,");
                    form.AppendLine("             locale: moment.locale('zh-cn')");
                    form.AppendLine("        });");
                }
            }
            form.AppendLine("        getForm();");
            form.AppendLine("    });");
            form.AppendLine("");
            form.AppendLine("    function getForm() {");
            form.AppendLine("        if (!!id) {");
            form.AppendLine("            frame.ajax({");
            form.AppendLine("                url: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/SetForm\")' + '?id=' + id,");
            form.AppendLine("                type: 'get',");
            form.AppendLine("                success: function (obj) {");
            form.AppendLine("                    if (obj.success) {");
            form.AppendLine("                        $('#form').setWebControls(obj.data);");
            form.AppendLine("                    }");
            form.AppendLine("                }");
            form.AppendLine("            });");
            form.AppendLine("        }");
            form.AppendLine("        else {");
            form.AppendLine("            var defaultData = {};");
            form.AppendLine("            $('#form').setWebControls(defaultData);");
            form.AppendLine("        }");
            form.AppendLine("    }");
            form.AppendLine("");
            form.AppendLine("    function saveForm(index) {");
            form.AppendLine("        if ($('#form').validate().form()) {");
            form.AppendLine("            var postData = $('#form').getWebControls({ Id: id });");
            form.AppendLine("            frame.ajax({");
            form.AppendLine("                url: '@Url.Content(\"/" + baseConfig.FileConfig.AreaName + "/" + baseConfig.FileConfig.ClassPrefix + "/SaveForm\")',");
            form.AppendLine("                type: 'post',");
            form.AppendLine("                data: postData,");
            form.AppendLine("                success: function (obj) {");
            form.AppendLine("                    if (obj.success) {");
            form.AppendLine("                        frame.msgSuccess(obj.message);");
            form.AppendLine("                        parent.searchGrid();");
            form.AppendLine("                        parent.layer.close(index);");
            form.AppendLine("                    }");
            form.AppendLine("                    else {");
            form.AppendLine("                        frame.msgError(obj.message);");
            form.AppendLine("                    }");
            form.AppendLine("                }");
            form.AppendLine("            });");
            form.AppendLine("        }");
            form.AppendLine("    }");
            form.AppendLine("</script>");
            form.AppendLine("");
            string codeForm = form.ToString();

            #endregion 

            #region 构建Menu

            StringBuilder menu = new StringBuilder();  
            string modulePrefix = baseConfig.FileConfig.AreaName.ToLower();
            string classPrefix = baseConfig.FileConfig.ClassPrefix.ToLower();
            menu.AppendLine($@"INSERT  INTO dbo.Sys_Menu
                                        ( ParentId ,
                                          Type ,
                                          Name ,
                                          Authorize ,
                                          UrlAddress ,
                                          Icon ,
                                          DisplayOrder ,
                                          EnabledMark ,
                                          DeletedMark ,
                                          CreatedOn ,
                                          CreatedBy ,
                                          UpdatedOn ,
                                          UpdatedBy
                                        )
                                VALUES  ( 父ID , -- ParentId - int
                                          3 , -- Type - int
                                          N'查询' , -- Name - nvarchar(50)
                                          N'{modulePrefix}:{classPrefix}:search' , -- Authorize - nvarchar(max)
                                          N'' , -- UrlAddress - nvarchar(200)
                                          N'' , -- Icon - nvarchar(200)
                                          1 , -- DisplayOrder - int
                                          1 , -- EnabledMark - bit
                                          0 , -- DeletedMark - bit
                                          GETDATE() , -- CreatedOn - datetime
                                          1 , -- CreatedBy - int
                                          NULL , -- UpdatedOn - datetime
                                          NULL  -- UpdatedBy - int
                                        ); 
                                INSERT  INTO dbo.Sys_Menu
                                        ( ParentId ,
                                          Type ,
                                          Name ,
                                          Authorize ,
                                          UrlAddress ,
                                          Icon ,
                                          DisplayOrder ,
                                          EnabledMark ,
                                          DeletedMark ,
                                          CreatedOn ,
                                          CreatedBy ,
                                          UpdatedOn ,
                                          UpdatedBy
                                        )
                                VALUES  ( 父ID , -- ParentId - int
                                          3 , -- Type - int
                                          N'新增' , -- Name - nvarchar(50)
                                          N'{modulePrefix}:{classPrefix}:add' , -- Authorize - nvarchar(max)
                                          N'' , -- UrlAddress - nvarchar(200)
                                          N'' , -- Icon - nvarchar(200)
                                          2 , -- DisplayOrder - int
                                          1 , -- EnabledMark - bit
                                          0 , -- DeletedMark - bit
                                          GETDATE() , -- CreatedOn - datetime
                                          1 , -- CreatedBy - int
                                          NULL , -- UpdatedOn - datetime
                                          NULL  -- UpdatedBy - int
                                        );
                                INSERT  INTO dbo.Sys_Menu
                                        ( ParentId ,
                                          Type ,
                                          Name ,
                                          Authorize ,
                                          UrlAddress ,
                                          Icon ,
                                          DisplayOrder ,
                                          EnabledMark ,
                                          DeletedMark ,
                                          CreatedOn ,
                                          CreatedBy ,
                                          UpdatedOn ,
                                          UpdatedBy
                                        )
                                VALUES  ( 父ID , -- ParentId - int
                                          3 , -- Type - int
                                          N'编辑' , -- Name - nvarchar(50)
                                          N'{modulePrefix}:{classPrefix}:edit' , -- Authorize - nvarchar(max)
                                          N'' , -- UrlAddress - nvarchar(200)
                                          N'' , -- Icon - nvarchar(200)
                                          3 , -- DisplayOrder - int
                                          1 , -- EnabledMark - bit
                                          0 , -- DeletedMark - bit
                                          GETDATE() , -- CreatedOn - datetime
                                          1 , -- CreatedBy - int
                                          NULL , -- UpdatedOn - datetime
                                          NULL  -- UpdatedBy - int
                                        );

                                INSERT  INTO dbo.Sys_Menu
                                        ( ParentId ,
                                          Type ,
                                          Name ,
                                          Authorize ,
                                          UrlAddress ,
                                          Icon ,
                                          DisplayOrder ,
                                          EnabledMark ,
                                          DeletedMark ,
                                          CreatedOn ,
                                          CreatedBy ,
                                          UpdatedOn ,
                                          UpdatedBy
                                        )
                                VALUES  ( 父ID , -- ParentId - int
                                          3 , -- Type - int
                                          N'删除' , -- Name - nvarchar(50)
                                          N'{modulePrefix}:{classPrefix}:delete' , -- Authorize - nvarchar(max)
                                          N'' , -- UrlAddress - nvarchar(200)
                                          N'' , -- Icon - nvarchar(200)
                                          4 , -- DisplayOrder - int
                                          1 , -- EnabledMark - bit
                                          0 , -- DeletedMark - bit
                                          GETDATE() , -- CreatedOn - datetime
                                          1 , -- CreatedBy - int
                                          NULL , -- UpdatedOn - datetime
                                          NULL  -- UpdatedBy - int
                                        );"); 
            string codeMenu = menu.ToString();

            #endregion

            var json = new
            {
                CodeEntity = HttpUtility.HtmlEncode(codeEntity),
                CodeParam = HttpUtility.HtmlEncode(codeParam),
                CodeController = HttpUtility.HtmlEncode(codeController),
                CodeIndex = HttpUtility.HtmlEncode(codeIndex),
                CodeForm = HttpUtility.HtmlEncode(codeForm),
                CodeMenu = HttpUtility.HtmlEncode(codeMenu)
            };
            return Content(DataResult<dynamic>.Success(json).ToJson());
        }

        #endregion

        #region 实体生成

        /// <summary>
        /// 实体生成
        /// </summary>
        /// <returns></returns>
        public ActionResult FormEntity()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ExportEntityJson(GeneratorEntityDto entityDto)
        {
            DataTable dt = GetTableFieldDataTable(entityDto.TableName);
            StringBuilder entity = new StringBuilder();
            entity.AppendLine("using SqlSugar;");
            entity.AppendLine("using System;");
            entity.AppendLine();
            entity.AppendLine($"namespace {entityDto.NameSpace}.Data");
            entity.AppendLine("{");
            entity.AppendLine("    /// <summary>");
            entity.AppendLine("    /// 日 期：" + DateTime.Now);
            entity.AppendLine("    /// 描 述：" + entityDto.ClassDescription + "实体类");
            entity.AppendLine("    /// </summary>");
            entity.AppendLine("    [SugarTable(\"" + entityDto.TableName + "\")]");
            entity.AppendLine("    public class " + entityDto.EntityName + " : BaseEntity");
            entity.AppendLine("    {");
            string entityColumn = string.Empty;
            string entityRemark = string.Empty;
            string datatype = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                entityColumn = dr["TableColumn"].ToString();
                if (entityColumn.ToUpper() == "ID") continue;
                entityRemark = dr["Remark"].ToString();
                datatype = dr["Datatype"].ToString();
                datatype = TableMappingHelper.GetPropertyDatatype(datatype);
                entity.AppendLine("        /// <summary>");
                entity.AppendLine("        /// " + entityRemark);
                entity.AppendLine("        /// </summary>");
                entity.AppendLine("        public " + datatype + " " + entityColumn + " { get; set; }");
            }
            entity.AppendLine("    }");
            entity.AppendLine("}");
            string codeEntity = entity.ToString();
            string codePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GeneratorFile", $"{entityDto.NameSpace}.Entity", "Entity", entityDto.EntityName + ".cs");
            if (!System.IO.File.Exists(codePath))
            {
                FileHelper.CreateFile(codePath, codeEntity);
            }
            return Content(DataResult<string>.Success(codePath, "导出成功").ToJson());
        }

        #endregion
    }
    public class BaseField
    {
        public static string[] BaseFieldList = new string[]
        {
            "Id",
            "EnabledMark",
            "DeletedMark", 
            "CreatedBy",
            "CreatedOn", 
            "UpdatedBy",
            "UpdatedOn"
        };
    }
    public class KeyValue
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public string Description { get; set; }
    }
}